package org.example.wx.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.common.utils.ResponseUtil;
import org.example.core.elasticsearch.service.ElasticSearchService;
import org.example.db.entity.Goods;
import org.example.db.mapper.GoodsMapper;
import org.example.wx.service.WxGoodsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@RestController
@Api(tags = "搜索")
@RequestMapping("/wx/search")
public class WxSearchController {


    ElasticSearchService elasticSearchService;
    GoodsMapper goodsMapper;

    public WxSearchController(ElasticSearchService elasticSearchService, GoodsMapper goodsMapper) {
        this.elasticSearchService = elasticSearchService;
        this.goodsMapper = goodsMapper;
    }

    @GetMapping("/goods")
    @ApiOperation("搜索商品")
    public Object goods(@RequestParam String keyword) throws IOException {

        String preTags = "<span style=\"color:red\"><b>";
        String postTags = "</b></span>";
        ArrayList<Map<String, Object>> query = elasticSearchService.query(keyword, 0, 10, preTags, postTags);

        ArrayList<Goods> goodsList = new ArrayList<>();
        for(Map<String, Object> map: query){

            Goods goods = goodsMapper.selectById(Long.parseLong((String)map.get("id")));
            goods.setName((String) map.get("name"));
            goodsList.add(goods);
        }

        return ResponseUtil.ok(goodsList);
    }
}
